package org.lyh.org.service.impl;

import org.lyh.base.service.impl.BaseServiceImpl;
import org.lyh.org.domain.Department;
import org.lyh.org.mapper.DepartmentMapper;
import org.lyh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;
    @Override
    public List<Department> queryTree() {

        List<Department> deptTree = new ArrayList<>();
        //获取所有部门
        List<Department> all = departmentMapper.selectAll();
        //将部门转为map方便根据id获取对象
        Map<Long, Department> map = all.stream().collect(Collectors.toMap(Department::getId, department -> department));
        for (Department department : all) {
            //将所有一级部门加入部门树
            if (Objects.isNull(department.getParentId())) {
                deptTree.add(department);
            } else {
                //将子部门根据其parentId添加到父部门children中
                map.get(department.getParentId()).getChildren().add(department);
            }
        }
        return deptTree;
    }

    @Override
    public void fixDirPathAndDate(Department department) {
        Long parentId =  department.getParent().getId();
        if (Objects.isNull(parentId)) {
            department.setDirPath("/"+department.getId());
        }else{
            department.setDirPath(departmentMapper.selectById(parentId).getDirPath()+"/"+department.getId());
        }
        //更新department
        departmentMapper.update(department);
    }
}
